/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */
package com.kkazmierczyk.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

/**
 * 
 * This is set of utilities related to JPA
 * 
 * @author kkazmierczyk
 * 
 */
public class JPAUtils {

	/**
	 * Converts array to map in that way, that parameters with unpaired unpaired
	 * indexes are keys and value of this key is element with next index of
	 * parameters table
	 * 
	 * @param params
	 * @return Converted map
	 * @throws ClassCastException
	 *             when parameter with unpaired index is not {@link String}
	 * @throws RuntimeException
	 *             when number of parameters is unpaired
	 */
	protected static Map<String, Object> arrayToMap(Object[] params) {
		if (params.length % 2 != 0) {
			throw new RuntimeException("Invalid number of params:"
					+ params.length);
		}
		final Map<String, Object> result = new HashMap<String, Object>(
				params.length / 2);
		for (int i = 0; i < params.length; i += 2) {
			result.put((String) params[i], params[i + 1]);
		}
		return result;
	}

	/**
	 * 
	 * Rollbacks entity transaction if it is not closed
	 * 
	 * @param tx
	 *            Entity transaction to close
	 */
	public static void closeQuietly(EntityTransaction tx) {
		if (tx != null && tx.isActive()) {
			tx.rollback();
		}
	}

	/**
	 * 
	 * Returns all entities of given type
	 * 
	 * @param <T>
	 *            Type of entity
	 * @param em
	 * @param tx
	 * @param clazz
	 *            Class of entity
	 * @return all entities of given type
	 */
	public static <T> List<T> getAllEntities(EntityManager em,
			EntityTransaction tx, Class<T> clazz) {
		return getEntitiesByParams(em, tx, clazz,
				new HashMap<String, Object>(0));
	}

	/**
	 * 
	 * Returns all entities of given type having specified parameters
	 * 
	 * @param <T>
	 *            Type of entity
	 * @param em
	 * @param tx
	 * @param clazz
	 *            Class of entity
	 * @param params
	 *            Map of parameters which must have returned objects of entity.
	 *            Key of map references to name of the entity field, value
	 *            references to expected value of the field
	 * @return all entities of given type having specified parameters
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> getEntitiesByParams(EntityManager em,
			EntityTransaction tx, Class<T> clazz, Map<String, Object> params) {
		StringBuilder sb = new StringBuilder("select t from " + clazz.getName()
				+ " t");
		if (!params.isEmpty()) {
			sb.append(" where ");
			for (Entry<String, Object> it : params.entrySet()) {
				if (it.getValue() != null) {
					sb.append("t." + it.getKey() + " = :"
							+ it.getKey().replace(".", "_") + " and ");
				} else {
					sb.append("t." + it.getKey() + " is null and ");
				}
			}
			sb.append("1=1");
		}

		final Query q = em.createQuery(sb.toString());

		// Setting parameters
		for (Entry<String, Object> it : params.entrySet()) {
			final String key = it.getKey();
			final Object value = it.getValue();
			if (value != null) {
				q.setParameter(key.replace(".", "_"), value);
			}
		}
		return q.getResultList();
	}

	/**
	 * 
	 * Returns all entities of given type having specified parameters.
	 * 
	 * @param <T>
	 *            Type of entity
	 * @param em
	 * @param tx
	 * @param clazz
	 *            Class of entity
	 * @param params
	 *            Array of parameters. Parameters with unpaired indexes refers
	 *            to name of entity field. Parameters with paired indexes refer
	 *            to expected value of field specified in previous element of
	 *            array
	 * @return all entities of given type having specified parameters * @throws
	 * @throws ClassCastException
	 *             when parameter with unpaired index is not {@link String}
	 * @throws RuntimeException
	 *             when number of parameters is unpaired
	 */
	public static <T> List<T> getEntitiesByParams(EntityManager em,
			EntityTransaction tx, Class<T> clazz, Object... params) {
		final Map<String, Object> paramsMap = arrayToMap(params);
		return getEntitiesByParams(em, tx, clazz, paramsMap);
	}

	/**
	 * 
	 * Returns single (first) entity of given type having specified parameters
	 * or {@code null} when such entity not exist
	 * 
	 * @param <T>
	 *            Type of entity
	 * @param em
	 * @param tx
	 * @param clazz
	 *            Class of entity
	 * @param params
	 *            Map of parameters which must have returned objects of entity.
	 *            Key of map references to name of the entity field, value
	 *            references to expected value of the field
	 * @return single (first) entity of given type having specified parameters
	 *         or {@code null} when such entity not exist
	 */
	public static <T> T getEntityByParams(EntityManager em,
			EntityTransaction tx, Class<T> clazz, Map<String, Object> params) {
		final List<T> result = getEntitiesByParams(em, tx, clazz, params);
		if (result.isEmpty()) {
			return null;
		} else {
			return result.get(0);
		}
	}

	/**
	 * 
	 * Returns single (first) entity of given type having specified parameters
	 * or {@code null} when such entity not exist
	 * 
	 * @param <T>
	 *            Type of entity
	 * @param em
	 * @param tx
	 * @param clazz
	 *            Class of entity
	 * @param params
	 *            Array of parameters. Parameters with unpaired indexes refers
	 *            to name of entity field. Parameters with paired indexes refer
	 *            to expected value of field specified in previous element of
	 *            array
	 * @return single (first) entity of given type having specified parameters
	 *         or {@code null} when such entity not exist * @throws
	 * @throws ClassCastException
	 *             when parameter with unpaired index is not {@link String}
	 * @throws RuntimeException
	 *             when number of parameters is unpaired
	 */
	public static <T> T getEntityByParams(EntityManager em,
			EntityTransaction tx, Class<T> clazz, Object... params) {
		final List<T> result = getEntitiesByParams(em, tx, clazz, params);
		if (result.isEmpty()) {
			return null;
		} else {
			return result.get(0);
		}
	}
}
